<?php
namespace app\filemanage\controller;

use think\Controller;
use think\Request;
use wenbin\filesystem\FileSystem;
use wenbin\format\Format;
use think\Cache;
use think\Session;

class Index extends Common
{
    public function index()
    {   
        $currentDir = input('get.pos') ? USER_ROOT_PATH . input('get.pos') : USER_ROOT_PATH;
        if ($this->_checkPath($currentDir) === false) {
        	return $this->error('非法操作');
        }
        if (is_dir($currentDir)) {
	      	$currentDir = rtrim($currentDir, DS); 
	      	if ($currentDir != realpath($currentDir)) {
	      		$this->redirect(url('index/index') . '?pos=' . FileSystem::getRelativePath(USER_ROOT_PATH, realpath($currentDir)));
			}     
	        $parentDir = realpath(substr($currentDir, 0, strrpos($currentDir, DS)));

	        $data['username'] = Session::get('username');
	        $data['parentPath'] = ($currentDir . DS) != USER_ROOT_PATH ? FileSystem::getRelativePath(USER_ROOT_PATH, $parentDir) : false;
	        $data['currentPath'] = FileSystem::getRelativePath(USER_ROOT_PATH, realpath($currentDir));
	        $files = scandir($currentDir);

	        $info = array();
	        if (count($files) > 2) {
		        foreach ($files as $value) {
		            if ($value !== '.' && $value !== '..') {
		                $path = $currentDir . DS . $value;

		                $isDir = is_dir($path);
		                $isDirArray[] = $isDir;

		                $info[] = [
			                'name'  => $value,
			                'type'  => $isDir,
			                'perms' => FileSystem::getPermissions($path),
			                'ctime' => date("Y-m-d H:i:s", filectime($path)),
			                'mtime' => date("Y-m-d H:i:s", filemtime($path)),
			                'atime' => date("Y-m-d H:i:s", fileatime($path)),
			                'size'  => Format::bytes(FileSystem::getSize($path, true)),
			                'path'  => $data['currentPath'] . $value,
		                ];
		            }
		        }
				array_multisort($isDirArray, SORT_DESC, $info);
	        }
	        $this->assign('info', $info);
	        $this->assign('data', $data);
	        return $this->fetch();
	    } else {
	    	return $this->error('文件夹不存在');
	    	// return $this->fetch('error'); 
	    }
    }

    private function _checkPath($path) {
    	if (is_dir($path)) {
    		return strpos(realpath($path) . DS, USER_ROOT_PATH);
    	} else {
    		return $this->_getDirDepth($path) >= $this->_getDirDepth(USER_ROOT_PATH);
    	}
    	
    }

    private function _getDirDepth($path) {
    	$path = rtrim($path, DS);
    	return substr_count($path, DS) - 2 * substr_count($path, '..' . DS);
    }
}
